<template>
  <div>
    <div style="display: flex; align-items: center; margin-bottom: 20px;">
      <a-input-search
          v-model:value="searchText"
          placeholder="请输入查询名称"
          enter-button="搜索"
      style="width: 250px; margin-right: 10px;"
      @search="handleSearch"
      ></a-input-search>

      <a-button type="primary"  @click="addEbook">
        新增
      </a-button>
    </div>
    <a-table :dataSource="ebooks" :columns="columns" :pagination="pagination" @change="handleTableChange" style="margin-top: 20px">
      <template #cover="{ text }">
        <img :src="text" alt="cover" width="50" />
      </template>
      <template #action="{ record }">
        <a-space>
          <a-button type="primary" @click="editEbook(record)">Edit</a-button>
          <a-button type="danger" @click="deleteEbook(record)">Delete</a-button>
          <router-link :to="`/admin/doc?ebookId=${record.id}`">
            <a-button type="danger">文档管理</a-button>
          </router-link>

        </a-space>
      </template>
    </a-table>

    <a-modal v-model:visible="editModalVisible" :title="editModalTitle" @ok="handleEditOk">
      <a-form :model="editForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="Name">
          <a-input v-model:value="editForm.name" />
        </a-form-item>
        <a-form-item label="Description">
          <a-input v-model:value="editForm.description" />
        </a-form-item>
        <a-form-item label="Cover">
          <a-input v-model:value="editForm.cover" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, onMounted } from 'vue';
import axios from 'axios';

export default defineComponent({
  setup() {
    const ebooks = ref([]);
    const pagination = ref({
      current: 1,
      pageSize: 4,
      total: 0,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '30'],
      showTotal: (total, range) => `${range[0]}-${range[1]} of ${total} items`,
    });
    const searchText = ref('');
    const editModalVisible = ref(false);
    const editModalTitle = ref('');
    const editForm = ref({});

    const columns = [
      {
        title: 'Cover',
        dataIndex: 'cover',
        slots: { customRender: 'cover' },
      },
      {
        title: 'Name',
        dataIndex: 'name',
      },
      {
        title: 'Description',
        dataIndex: 'description',
      },
      {
        title: 'Action',
        key: 'action',
        slots: { customRender: 'action' },
      },
    ];

    const fetchData = async (params) => {
      try {
        console.log(params,'打印结果')
        const response = await axios.get('/ebook/list', { params });
        ebooks.value = response.data.content.list;
        pagination.value.total = response.data.content.total;
        console.log(response.data.content.list)
      } catch (error) {
        console.error('Failed to fetch data:', error);
      }
    };


    const handleTableChange = (paginationObj) => {
      pagination.value.current = paginationObj.current;
      pagination.value.pageSize = paginationObj.pageSize;
      fetchData({
        page: pagination.value.current,
        size: pagination.value.pageSize,
        name: searchText.value,
      });
    };

    const handleSearch = () => {
      fetchData({
        page: 1,
        size: pagination.value.pageSize,
        name: searchText.value,
      });
    };

    const addEbook = () => {
      editForm.value = {};
      editModalTitle.value = 'Add Ebook';
      editModalVisible.value = true;
    };

    const editEbook = (record) => {
      editForm.value = { ...record };
      editModalTitle.value = 'Edit Ebook';
      editModalVisible.value = true;
      console.error(editForm);
    };

    const handleEditOk = async () => {
      try {
        console.log('打印啊啊啊啊')
        console.log(editForm.value)
        if (editForm.value.id) {
          await axios.post('/ebook/save', editForm.value);
        } else {
          await axios.post('/ebook/save', editForm.value);
        }
        editModalVisible.value = false;
        fetchData({
          page: pagination.value.current,
          size: pagination.value.pageSize,
          name: searchText.value,
        });
      } catch (error) {
        console.error('Update failed:', error);
      }
    };

    const deleteEbook = async (record) => {
      try {
        console.log('Record to delete:', record);
        await axios.delete(`/ebook/delete/${record.id}`);

        // 获取删除后的数据
        const response = await axios.get('/ebook/list', {
          params: {
            page: pagination.value.current,
            size: pagination.value.pageSize,
            name: searchText.value,
          },
        });

        // 检查当前页是否还有数据
        if (response.data.content.list.length === 0 && pagination.value.current > 1) {
          // 如果当前页没有数据且不是第一页,将当前页码减1
          pagination.value.current -= 1;
        }

        // 重新获取数据
        fetchData({
          page: pagination.value.current,
          size: pagination.value.pageSize,
          name: searchText.value,
        });
      } catch (error) {
        console.error('Delete failed:', error);
      }
    };

    onMounted(() => {
      fetchData({
        page: pagination.value.current,
        size: pagination.value.pageSize,
      });
    });

    return {
      ebooks,
      pagination,
      searchText,
      editModalVisible,
      editModalTitle,
      editForm,
      columns,
      handleTableChange,
      handleSearch,
      addEbook,
      editEbook,
      handleEditOk,
      deleteEbook,
    };
  },
});
</script>